//
//  WBNetworkManger+Extension.swift
//  swiftweibo
//
//  Created by ffxk007 on 2017/6/18.
//  Copyright © 2017年 ffxk007. All rights reserved.
//

import Foundation
//MARK: -封装新浪微博的网络请求
extension WBNetworkManger {
    func statusList(since_id:Int64 = 0,max_id:Int64 = 0,completion:@escaping (_ list:[[String:AnyObject]]?,_ isSuccess:Bool)->()){
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let parmas = ["since_id":"\(since_id)","max_id":"\(max_id > 0 ? max_id - 1 : 0)"]
        
        tokenRequest(method:.GET, URLString: urlStr, parameters:parmas as [String : AnyObject]) { (json, isSucess) in
            
            /// 从json中获取statuses字典数组如果as失败result就等于nil
            let result =  json?["statuses"] as? [[String:AnyObject]]
            completion(result, isSucess)
            ///  Nil is not compatible with expected argument type '[String : AnyObject]'
           
        }

    }
    
    func unreadCount(completion:@escaping (_ count:Int)->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        let urlstring = "https://rm.api.weibo.com/2/remind/unead_count.json"
        
        let params = ["uid":uid]
        
        tokenRequest(URLString: urlstring, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            let dic = json as? [String:AnyObject]
            let count = dic?["status"] as? Int
            completion(count ?? 0)
        }
    }
}

// MARK: - 用户信息
extension WBNetworkManger {
    
    /// 加载用户信息-用户登录后立即执行
    func loadUserIonfo(completion:@escaping (_ dict:[String:AnyObject])->()) {
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let params = ["uid":uid]
        //发起网络请求
        tokenRequest(URLString: urlStr, parameters: params as [String : AnyObject]) { (json, isSuccess) in
//            print(json ?? [:])
            //完成回调
            completion(json as? [String:AnyObject] ?? [:])
            
        }
    }
}

// MARK: - Oauth相关
extension WBNetworkManger {
    
    /// 加载ACCESSTOKEN
    //异步返回什么
    
    /// 加载ACCESSTOKEN
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 完成回调，是否成功
    func loadAccessToken(code:String,completion:@escaping (_ isSuccess:Bool)->()) {
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":WBAppkey,
                      "client_secret":WBAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WBRedirectURL]
        request(method: .Post, URLString: urlStr, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            //FIXME:有可能有问题
            print(json as Any)
            //如果请求失败，对账户数据不会有任何影响
            //直接用字典设置useraccount的属性
            self.userAccount.yy_modelSet(with: json as? [String:AnyObject] ?? [:])
            
//            print(self.userAccount)
            
            
            //加载当前用户信息
            self.loadUserIonfo(completion: { (dict) in
                print(dict)
                //使用用户信息字典设置用户账户信息(昵称和头像)
                self.userAccount.yy_modelSet(with: dict)
                //保存模型
                self.userAccount.saveAccount()
                //完成回调
                completion(isSuccess)
            })
            
           
        }
    }
}
